from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.contrib.auth.models import User
from .models import Article

#-----ckeditor begin-----#
from . import forms as myform

def goSignupPage(request):
    return render(request,'signup.html',{'form':myform.SignupForm})

from django import forms
class ArticleModelForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['title','content']

#-----ckeditor end-----#

def goBlogIndexPage(request):
    articles = Article.objects.all().order_by('-updateDate','-createDate')
    user = request.user
    username = ''
    if user != None :
        username = user.get_username()
    return render(request,'blog_index.html',{'articles':articles,'username':username})

@login_required
def goBlogPersonalIndexPage(request):
    user = request.user
    username = user.get_username()
    articles = Article.objects.all().filter(author_username=username).order_by('-updateDate','-createDate')
    return render(request,'personalmain.html',{'articles':articles,'username':username})

def userLogin(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        next = request.POST['next']
        return redirect(next)
    else:
        return redirect('login')

def userLogout(request):
    logout(request)
    return redirect("/blog/")

def goUserRegisterPage(request):
    return render(request,'register.html')

def userRegister(request):
    if request.method == 'POST':
        form = myform.SignupForm(request.POST)
        message = {}
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            confirmpassword = form.cleaned_data['confirmpassword']
            message['username'] = username
            if password != confirmpassword:
                message['info'] = 'password not equal!'
            else :
                user = User.objects.create_user(username,email,password)
                user.save()
                message['success'] = 'success'
        return render(request,'register.html',{'message':message,'form':form})
    return redirect(settings.LOGIN_URL)

@login_required
def saveArticle(request):
    if request.method == 'GET' :
        form = ArticleModelForm()
        return render(request,'addarticle.html',{'form':form,'title_value':'','id_value':'','username':request.user.get_username()})
    elif request.method == 'POST' :
        articleForm = ArticleModelForm(request.POST)
        if articleForm.is_valid():
            articleTemp = articleForm.save(commit=False)
            article_id = request.POST.get('article_id')
            if article_id == '':
                user = request.user
                article = Article()
                article.title = articleTemp.title
                article.content = articleTemp.content
                article.author_username = user.get_username()
                article.save()
                return redirect("/blog/")
            if article_id != '':
                article = Article.objects.get(article_id__exact=article_id)
                article.title = articleTemp.title
                article.content = articleTemp.content
                article.save()
                return redirect("/blog/arch/read/"+article_id)
        return render(request,'addarticle.html',{'form':articleForm,'title_value':request.POST.get('title'),'id_value':request.POST.get('article_id'),'username':request.user.get_username()})

@login_required
def getArticleById(request,opertype,articleId):
    article = Article.objects.get(article_id__exact=articleId)
    user = request.user
    is_author = '0'
    if article.author_username == user.get_username():
        is_author = '1'
    goHtml = 'readarticle.html'
    form = article
    if opertype == 'edit':
        form = ArticleModelForm(instance=article)
        goHtml = 'editarticle.html'
    elif opertype == 'delete' and is_author == '1':
        article.delete()
        return redirect("/blog/personal/")
    elif opertype == 'asydelete':
        return 'json'
    return render(request,goHtml,{'article':article,'form':form,'username':user.get_username(),'is_author':is_author})

def readArticleById(request,articleId):
    form = Article.objects.get(article_id__exact=articleId)
    article_user_name = form.author_username
    user = request.user
    is_author = '0'
    user_name = ''
    if user != None :
        user_name = user.get_username()
        if user_name == article_user_name :
            is_author = '1'
    return render(request,'readarticle.html',{'form':form,'is_author':is_author,'username':user_name})